<template>
	<view class="reset-psw">
		<!-- 顶部文字 -->
		<!-- <view class="title">设置新密码</view> -->
		<u-form ref="loginFormRef" :model="formData" :rules="rules" errorType="toast" labelPosition="top" labelWidth="auto">
			<u-form-item prop="originalPassword" label="原密码">
				<u-input v-model="formData.originalPassword" type="passWord" clearable border="bottom" placeholder="请输入原密码" />
			</u-form-item>
			<u-form-item prop="newPassword" label="新密码">
				<u-input v-model="formData.newPassword" type="passWord" clearable border="bottom" placeholder="请设置新密码" />
			</u-form-item>
			<u-form-item prop="repeatNewPassword" label="确认密码">
				<u-input v-model="formData.repeatNewPassword" type="passWord" clearable border="bottom" placeholder="请再次输入新密码" />
			</u-form-item>
		</u-form>
		<button class="uni-btn" type="primary" :loading="loading" @click="modifyPwd">确 认</button>
	</view>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { UserPswModify } from '@/types/type';
import { useUserStore } from '@/stores/useUserStore';
import { modifyPasswordApi } from '@/api/index';

/**
 * 表单数据定义
 */
const formData = reactive<UserPswModify>({
	originalPassword: '',
	newPassword: '',
	repeatNewPassword: ''
});

/**
 * 密码一致性校验
 */
const checkRepeatPsw = (rule: object, value: string, callback: any) => {
	if (formData.newPassword === value) {
		callback();
	}
	callback(new Error('确认密码与新密码不一致，请重试'));
};

/**
 * 密码长度校验
 */
function passwordValidator(rule: any, value: any, callback: any) {
	if (value.length < 6) {
		callback(new Error('密码长度不少于6位'));
	} else {
		callback();
	}
}

/**
 * 表单数据规则
 */
const rules = reactive({
	originalPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
	newPassword: [
		{ required: true, message: '请设置新密码', trigger: 'blur' },
		{ required: true, validator: passwordValidator, trigger: 'blur' }
	],
	repeatNewPassword: [
		{ required: true, message: '请再次输入新密码', trigger: 'blur' },
		{ required: true, validator: passwordValidator, trigger: 'blur' },
		{ required: true, validator: checkRepeatPsw, trigger: 'blur' }
	]
});

/**
 * 修改密码
 */
const loading = ref(false);
const loginFormRef = ref();
function modifyPwd() {
	loginFormRef.value.validate().then(async () => {
		loading.value = true;
		const { newPassword, originalPassword } = formData;
		modifyPasswordApi({ newPassword, originalPassword })
			.then((e) => {
				uni.showToast({
					icon: 'none',
					title: '修改成功，即将重新登录...'
				});
				setTimeout(() => {
					useUserStore().logout();
				}, 1000);
			})
			.finally(() => {
				loading.value = false;
			});
	});
}
</script>

<style lang="scss" scoped>
.reset-psw {
	padding: $uni-page-padding;
	padding-top: 10px;
	.title {
		padding: 30px 0 20px;
		font-weight: 400;
		font-size: 22px;
	}
	.u-form-item {
		margin-top: 10px;
	}
	.u-input {
		padding: 8px 0 !important;
	}
	.uni-btn {
		margin-top: 30px;
		border-radius: 24px;
	}
}
</style>
